package com.example.dragview.demo

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View

class AutoDragView : View {
  private var lastX: Float = 0f
  private var lastY: Float = 0f

  constructor(context: Context) : this(context, null)
  constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
  constructor(
    context: Context,
    attrs: AttributeSet?,
    defStyleAttr: Int
  ) : super(context, attrs, defStyleAttr)

  @SuppressLint("ClickableViewAccessibility")
  override fun onTouchEvent(event: MotionEvent?): Boolean {
    val x = event?.x ?: 0f
    val y = event?.y ?: 0f
    when (event?.action) {
      MotionEvent.ACTION_DOWN -> {
        lastX = x
        lastY = y
      }
      MotionEvent.ACTION_MOVE -> {
        val offsetX = x - lastX
        val offsetY = y - lastY
        offsetLeftAndRight(offsetX.toInt())
        offsetTopAndBottom(offsetY.toInt())
      }
    }
    return true
  }

  override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec)
    Log.d(TAG, "onMeasure")
  }

  override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
    super.onLayout(changed, left, top, right, bottom)
    Log.d(TAG, "onLayout $left-$right/$top-$bottom")
  }

  override fun onDraw(canvas: Canvas?) {
    super.onDraw(canvas)
    Log.d(TAG, "onDraw")
  }

  companion object {
    private const val TAG = "AutoDragView"
  }
}